<template>
  <el-dialog :title="title" :visible.sync="dialogFormVisible" width="600px" @close="close">
    <el-form ref="form" label-width="120px" :model="form" :rules="rules">
      <el-form-item class="product-ids" prop="product.ids">
        <el-form-item label="微信产品id" prop="product.id">
          <el-input v-model.trim="form.product.id" autocomplete="off" />
        </el-form-item>

        <el-form-item label="淘宝产品id" prop="product.tmallId">
          <el-input v-model.trim="form.product.tmallId" autocomplete="off" />
        </el-form-item>
        <el-form-item class="product-dy-ids" label="抖音产品id" prop="product.dyId">
          <el-input v-model.trim="form.product.dyId" autocomplete="off" />
        </el-form-item>
      </el-form-item>

      <el-form-item label="产品名称" prop="product.name">
        <el-input v-model.trim="form.product.name" autocomplete="off" />
      </el-form-item>
      <el-form-item label="副标题" prop="product.title">
        <el-input v-model.trim="form.product.title" autocomplete="off" />
      </el-form-item>
      <el-form-item label="二级分类" prop="product.class">
        <el-input v-model.trim="form.product.class" autocomplete="off" />
      </el-form-item>
      <el-form-item label="优先级（数字)" prop="product.priority">
        <el-input v-model.number="form.product.priority" autocomplete="off" />
      </el-form-item>
      <el-form-item label="推荐理由" prop="product.desc">
        <el-input v-model.trim="form.product.desc" autocomplete="off" type="textarea" />
      </el-form-item>

      <el-form-item ref="Addfrom" label="产品图片url" prop="product.url">
        <el-row style="padding-bottom: 10px">
          <el-col>
            <el-input v-model.trim="form.product.url" autocomplete="off" :disabled="true" />
          </el-col>
        </el-row>
        <el-row>
          <!-- <el-upload
            v-model="fromList"
            action=""
            :before-upload="beforeUpload"
            class="avatar-uploader"
            :http-request="handleUpload"
            :on-preview="handlePreview"
          >
            <el-button type="primary">上传产品图片</el-button>
          </el-upload> -->
          <el-upload
            v-model="form.product.url"
            action=""
            :before-upload="beforeUpload"
            class="avatar-uploader"
            :http-request="uploadURL"
            :multiple="false"
            :show-file-list="false"
          >
            <el-button type="primary">{{ isAdd ? '上传' : '更改' }}产品图片</el-button>
          </el-upload>
        </el-row>
      </el-form-item>
      <el-form-item label="产品标签" prop="tags">
        <el-row v-for="(item, index) in form.tags" :key="`${form.product.id}-${index}`">
          <el-col :span="10">
            <el-form-item
              label="维度"
              label-width="52px"
              :prop="`tags.${index}.index`"
              :rules="tagsIndexRules"
            >
              <el-input v-model="item.index" placeholder="维度" />
            </el-form-item>
          </el-col>
          <!-- /* eslint-disable */ -->
          <div style="width: 5px; height: 10px; float: left"></div>
          <el-col :span="10">
            <el-form-item
              label="标签"
              label-width="52px"
              :prop="`tags.${index}.tag`"
              :rules="tagsTagRules"
            >
              <el-input v-model="item.tag" placeholder="标签" />
            </el-form-item>
          </el-col>
          <!-- /* eslint-disable */ -->
          <div style="width: 5px; height: 10px; float: left"></div>
          <el-col :span="2">
            <el-form-item>
              <el-button type="danger" @click="handleDelTags(form.tags, index)">删除</el-button>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-form-item>
            <el-button type="primary" @click="handleAddTags(form.tags)">新增标签</el-button>
          </el-form-item>
        </el-row>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" @click="save">保 存</el-button>
    </div>
  </el-dialog>
</template>

<script>
  import { doEdit } from '@/api/configration'
  import { uploadOSSImage, client, getFileNameUUID } from '@/utils/uploadOSS'
  export default {
    name: 'ProductTableEdit',
    data() {
      return {
        fromList: {},
        Addfrom: { url: '' },
        isAdd: false,
        form: {
          product: { ids: undefined, url: '' },
          tags: [],
        },
        list: {},

        tagsIndexRules: [{ required: true, trigger: 'blur', message: '请输入维度' }],
        tagsTagRules: [{ required: true, trigger: 'blur', message: '请输入标签' }],
        idsRules: [{ trigger: 'blur', message: '请输入产品id' }],
        rules: {
          'product.ids': [{ required: true, trigger: 'blur', message: '产品id最少一项必填' }],
          'product.name': [{ required: true, trigger: 'blur', message: '请输入产品名称' }],
          'product.title': [{ required: true, trigger: 'blur', message: '请输入产品副标题' }],
          'product.class': [{ required: true, trigger: 'blur', message: '请输入产品二级分类' }],
          'product.priority': [
            { required: true, trigger: 'blur', message: '请输入产品优先级' },
            { type: 'number', message: '产品优先级须为整数数字', trigger: 'blur' },
          ],
          'product.desc': [{ required: true, trigger: 'blur', message: '请输入产品推荐理由' }],
          'product.url': [
            { required: true, trigger: 'change', message: '请输入产品图片url' },
            { type: 'url', message: '产品图片url需要链接', trigger: 'change' },
          ],
          tags: [{ required: true, trigger: 'blur', message: '请新增产品标签' }],
        },
        title: '',
        dialogFormVisible: false,
        defaultContinuous: '',
      }
    },
    created() {},
    methods: {
      getFileName(name) {
        return name.substring(name.lastIndexOf('.')) //.txt
      },
      beforeUpload(file) {
        console.log('上传图片 beforeUpload option', file)

        // 限制上传类型
        const fileExtensions =
          this.getFileName(file.name) === '.jpeg' ||
          this.getFileName(file.name) === '.jpg' ||
          this.getFileName(file.name) === '.png' ||
          this.getFileName(file.name) === '.webp' ||
          this.getFileName(file.name) === '.gif' ||
          this.getFileName(file.name) === '.JPG'
        //限制的上限为20M
        const max20M = file.size / 1024 / 1024 < 4
        if (!fileExtensions) {
          this.$baseMessage('上传图片只能是 jpeg/jpg/png/webp/gif/JPG 格式!', 'error')
        }
        if (!max20M) {
          this.$baseMessage('上传文件大小不能超过 4MB!', 'error')
        }
        return fileExtensions && max20M
      },
      uploadURL(file) {
        console.log('上传图片 handleUpload option', file)

        var fileName = 'ProductImage/' + `${Date.parse(new Date())}` + '.jpg' //定义唯一的文件名
        //定义唯一的文件名，打印出来的uid其实就是时间戳
        client()
          .multipartUpload(fileName, file.file, {
            progress: function (percentage, cpt) {
              console.log('打印进度', percentage)
            },
          })
          .then((result) => {
            //此处为给自己属性进行赋值，
            //根据需要可能项目还需对自己的数据库进行保存
            /* eslint-disable */
            this.form.product.url =
              'https://hxsw-jihuo-applet-meidaojia.oss-cn-beijing.aliyuncs.com/' + fileName
            // this.form.product.url = this.Addfrom.url
            console.log('this.$refs', this.$refs)
            // 上传成功后，手动验证一次表单
            // this.$refs.Addfrom.validate()
          })
          .catch(() => {
            this.$baseMessage('上传图片到oss失败请重新上传~', 'error')
          })
      },
      submitUpload() {
        this.$refs.upload.submit()
      },
      handleRemove(file, fileList) {
        console.log(file, fileList)
      },
      handlePreview(file) {
        console.log(file)
      },
      // 上传图片
      async handleUpload(option) {
        // 获取文件的后缀名
        // let objName = getFileNameUUID()
        var obj = option.file.name
        var index = obj.lastIndexOf('.')
        obj = obj.substring(index, obj.length)
        // 生成的文件名，保留文件后缀名，进行拼接
        let objName = getFileNameUUID() + this.getFileName(option.file.name)
        console.log('上传图片 handleUpload option', option)
        try {
          await uploadOSSImage(option).catch((err) => {
            console.log('上传图片 handleUpload err', err)
            this.$baseMessage('上传图片到oss失败请重新上传', 'error')
          })
        } catch (error) {
          console.log('上传图片 handleUpload error', error)
          this.$baseMessage('上传图片到oss失败请重新上传', 'error')
        }
        // this.$refs.Addfrom.validateField('url')
        // // 调用 ali-oss 中的方法,flieName是存放的文件夹名称，可自己定义
        // put(`flieName/${objName}`, option.file).then(res => {
        //   console.log(res,'res')
        //   // 上传成功之后，转换真实的地址
        //   signatureUrl(`flieName/${objName}`).then(res => {
        //       console.log(res)
        //   })
        // })
      },
      // 新增标签
      handleAddTags(tags) {
        if (tags && Array.isArray(tags)) {
          tags.push({ index: '', tag: '' })
        }
      },
      handleDelTags(tags, index) {
        // 删除标签
        if (tags && Array.isArray(tags)) {
          tags.splice(index, 1)
        }
      },
      showEdit(list, row) {
        console.log('显示', list)
        if (!row) {
          this.title = '添加产品'
          this.isAdd = true
          this.from = { product: { url: '', ids: undefined }, tags: [] }
        } else {
          this.title = '编辑产品'
          this.form = Object.assign({}, row)
          this.isAdd = false
          // this.defaultContinuous = this.from.continuous
        }
        // this.from.pr
        this.list = list
        this.dialogFormVisible = true
      },
      close() {
        console.log('close----')
        this.$emit('fetch-data')
        this.dialogFormVisible = false
        this.$refs['form'].resetFields()
        this.form = this.$options.data().form
        this.from = {
          product: { url: '', ids: false },
          tags: [],
        }
        this.Addfrom.url = ''
      },
      save() {
        console.log(this.form, '....save.....start....', this.list)
        if (this.form && typeof this.form === 'object') {
          let { product } = this.form
          if (product && typeof product === 'object') {
            product.ids = product.id || product.tmallId || product.dyId
          }
        }
        this.$refs['form'].validate(async (valid) => {
          if (valid) {
            this.$forceUpdate()
            console.log(this.form, '....save.........', this.list)
            // const props = getEditPrizeConfigProps(this.form, this.list, this.add)
            // console.log('传递参数---', props, this.$options)
            // const { error, data } = await doEdit(props)
            if (
              this.form &&
              typeof this.form === 'object' &&
              this.list &&
              Array.isArray(this.list)
            ) {
              if (this.isAdd) {
                this.list.unshift(this.form)
              } else {
                this.list.map((item) => {
                  if (item && typeof item === 'object') {
                    let { product } = this.form
                    let { product: p } = item

                    if (
                      p &&
                      typeof p === 'object' &&
                      product &&
                      typeof product === 'object' &&
                      p.id === product.id
                    ) {
                      item = this.form
                    }
                  }
                })
              }
            }
            const props = {
              configValue: this.list,
              configItem: 'Product',
            }
            let { data, error } = await doEdit(props).catch((err) => {
              this.$baseMessage('接口报错', 'error')
            })
            console.log('..data...', data)
            if (error) {
              this.$baseMessage(error || '接口报错', 'error')
            } else {
              this.$baseMessage('操作成功', 'success')
              this.close()
            }
          } else {
            return false
          }
        })
      },
    },
  }
</script>
<style>
  /* .product-ids {
    margin-bottom: 0 !important;
  } */
  .product-ids > .el-form-item__content {
    margin-left: 0 !important;
  }
  .product-ids .el-form-item--small.el-form-item.product-dy-ids {
    margin-bottom: 0 !important;
  }
  .product-ids.is-error .el-form-item--small.el-form-item:last-of-type {
    margin-bottom: 0 !important;
  }
  .product-ids .el-form-item__error {
    margin-left: 120px !important;
  }
</style>
